package com.agrimall.servlet.merchant;

import com.agrimall.entity.ChatMessage;
import com.agrimall.entity.ConsultationSession;
import com.agrimall.entity.User;
import com.agrimall.mapper.ChatMessageMapper;
import com.agrimall.mapper.ConsultationSessionMapper;
import com.agrimall.util.MyBatisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商家端咨询管理Servlet
 */
@WebServlet("/merchant/consultation")
public class ConsultationManageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User merchant = (User) session.getAttribute("merchant");
        
        if (merchant == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if ("history".equals(action)) {
            // 返回历史消息（JSON格式）
            getHistoryMessages(request, response, merchant);
        } else if ("clearUnread".equals(action)) {
            // 清除未读消息数
            clearUnreadCount(request, response, merchant);
        } else {
            // 咨询列表页面
            listConsultations(request, response, merchant);
        }
    }
    
    /**
     * 咨询列表
     */
    private void listConsultations(HttpServletRequest request, HttpServletResponse response, User merchant)
            throws ServletException, IOException {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            ConsultationSessionMapper mapper = sqlSession.getMapper(ConsultationSessionMapper.class);
            List<ConsultationSession> sessions = mapper.selectByMerchantId(merchant.getUserId());
            request.setAttribute("sessions", sessions);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "加载咨询列表失败：" + e.getMessage());
        } finally {
            sqlSession.close();
        }
        
        request.getRequestDispatcher("/merchant/consultation/list.jsp").forward(request, response);
    }
    
    /**
     * 获取历史消息
     */
    private void getHistoryMessages(HttpServletRequest request, HttpServletResponse response, User merchant)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String sessionId = request.getParameter("sessionId");
            if (sessionId == null || sessionId.trim().isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "会话ID不能为空");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                ChatMessageMapper mapper = sqlSession.getMapper(ChatMessageMapper.class);
                List<ChatMessage> messages = mapper.selectBySessionId(sessionId, 0, 1000);
                
                // 清除商家未读消息数
                ConsultationSessionMapper sessionMapper = sqlSession.getMapper(ConsultationSessionMapper.class);
                sessionMapper.clearUnreadCount(sessionId, 1);
                sqlSession.commit();
                
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("messages", messages);
                out.print(objectMapper.writeValueAsString(result));
            } finally {
                sqlSession.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "加载历史消息失败：" + e.getMessage());
            out.print(objectMapper.writeValueAsString(result));
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 清除未读消息数
     */
    private void clearUnreadCount(HttpServletRequest request, HttpServletResponse response, User merchant)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String sessionId = request.getParameter("sessionId");
            if (sessionId == null || sessionId.trim().isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "会话ID不能为空");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                ConsultationSessionMapper mapper = sqlSession.getMapper(ConsultationSessionMapper.class);
                mapper.clearUnreadCount(sessionId, 1); // 1表示商家
                sqlSession.commit();
                
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("message", "清除成功");
                out.print(objectMapper.writeValueAsString(result));
            } catch (Exception e) {
                sqlSession.rollback();
                e.printStackTrace();
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "清除失败：" + e.getMessage());
                out.print(objectMapper.writeValueAsString(result));
            } finally {
                sqlSession.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "清除失败：" + e.getMessage());
            out.print(objectMapper.writeValueAsString(result));
        } finally {
            out.flush();
            out.close();
        }
    }
}

